package me.yangteng.zhihudaily.util;

import android.content.Context;
import android.util.Log;

import com.google.gson.Gson;

import me.yangteng.zhihudaily.model.StoriesBean;
import me.yangteng.zhihudaily.model.StoriesList;
import me.yangteng.zhihudaily.model.Story;

/**
 * Created by MorenYang on 2017/12/26.
 */

public class CachedStoryFetcher {
  private static final String TAG = "CachedStoryFetcher";
  private LocalStoryLoader localStoryLoader;
  private Gson gson;
  private PreferenceLoader preferenceLoader;

  public CachedStoryFetcher(Context context) {
    localStoryLoader = new LocalStoryLoader(context);
    preferenceLoader = new PreferenceLoader(context);
    gson = new Gson();
    Log.d(TAG, "Enable auto cached " + preferenceLoader.isEnableAutoCached());
  }

  public void fetchStories(StoriesList storiesList) {
    if (!preferenceLoader.isEnableAutoCached()) return;
    for (StoriesBean storiesBean : storiesList.getStories()) {
      loadStory(storiesBean);
    }
  }

  private void loadStory(StoriesBean storiesBean) {
    if (localStoryLoader.has(Story.STORAGE_PREFIX + storiesBean.getId())) return;
    Log.d(TAG, "cached httpFetch " + storiesBean.getId());
    HttpLoader httpLoader = new HttpLoader();
    httpLoader.setHttpLoaderListener(new HttpLoader.HttpLoaderListener() {
      @Override
      public void onGetHttpString(String string) {
        Story story = gson.fromJson(string, Story.class);
        story.setStorageKey(Story.STORAGE_PREFIX + story.getId());
        localStoryLoader.save(story);
      }

      @Override
      public void onError(Exception e) {

      }
    });
    httpLoader.execute(Url.STORY_CONTENT + storiesBean.getId());
  }
}
